def init(context):
    get_iwencai('非ST,非停牌,股票简称不包含退,收盘价从小到大排名前80', "wencai_res")
    #get_iwencai('净利润增长大于0%,股价位于20日均线上方,昨天主力资金净流入/流通市值大于0.001,非ST', "wencai_res")
    context.hold = []
    context.hold_date = {}
class Stock():
    def __init__(self,name,context):
        self.name = name
        self.context = context
        self.closeprice = history(self.name, ['close'], 20, '1d', False, 'pre', is_panel=1)
    def get_ma5(self):
        return self.closeprice['close'].iloc[-5:].mean()
    def get_ma20(self):
        return self.closeprice['close'].mean()
    def golden_cross(self):
        return self.get_ma5() > self.get_ma20()
    def should_purge(self,pos=-0.1):
        """
        止损,默认10%
        """
        info = self.context.portfolio.positions[self.name]
        if not info:
            return True
        #log.info("{} 盈亏 {}".format(self.name),float(info.pnl)/float(info.market_value) )
        try:
            res = float(info.pnl)/float(info.market_value)  <= pos
            return res
        except Exception as  e:
            log.info("{} 盈亏 {} {}".format(self.name),float('%.2f' % info.pnl),float('%.2f' % info.market_value))
            raise e

            
    def normal_cycle(self,days=30):
        """
        交割周期,默认20天
        """
        info = self.context.portfolio.positions[self.name]
        date = self.context.hold_date.get(self.name)
        return (info.datetime - date).days >= days

        
    def bonus(self):
        info = self.context.portfolio.positions[self.name]
        return info.pnl
    def hold(self):
        info = self.context.portfolio.positions[self.name]
        return  info.amount
    def is_hold(self):
        info = self.context.portfolio.positions[self.name]
        log.info("{}持仓数量{}".format(self.name,info.amount))

        return  info.amount !=0
        
class MyAcountInfo():
    def __init__(self,context):
        self.context = context
        self.hold_list  = self.context.hold
    def is_emtpy(self):
        return len(self.hold()) == 0
    def is_full(self):
        return len(self.hold()) >=10
    def hold(self):
        return list(self.context.hold)
    def add_hold(self,stock):
        self.context.hold.append(stock)
    def remove_hold(self,stock):
        self.context.hold.remove(stock)
    def refresh(self):
        """脏数据清理"""
        for stock in self.hold_list:
            h = Stock(stock,self.context)
            if h.hold() == 0 :
                self.remove_hold(stock)
                self.context.hold_date.pop(stock)
        self.hold_list  = self.context.hold
    
def sold_stock(name,account,context):
    res = order_target(name,0)
    if res is None:
        return

    account.remove_hold(name)
    context.hold_date.pop(name)
    
def buy_stock(name,account,context):
    res = order_target_percent(name,0.1)
    if res is None:
        return
    account.add_hold(name)
    context.hold_date.update({name:context.portfolio.positions[name].datetime})
    
def handle_bar(context, bar_dict):
    my_account = MyAcountInfo(context)
    my_account.refresh()
    my_account = MyAcountInfo(context)

    log.info("问财列表{}".format(context.wencai_res))

    log.info("持仓列表{}".format(context.hold))
    if not my_account.is_emtpy():
        for hold in context.hold:
            h = Stock(hold,context)
            log.info("检查持仓{},{}".format(h.name,h.hold()))

            if h.should_purge():
                log.info("{}止损，全卖".format(h.name))
                sold_stock(h.name,my_account,context)
                continue
            if h.normal_cycle():
                log.info("{}交割，全卖,盈利{}".format(h.name,h.bonus()))
                
                sold_stock(h.name,my_account,context)
    # log.info("问财列表 {}".format(context.wencai_res))
            
    for stock in context.wencai_res:
        if my_account.is_full():
            log.info("持仓满，不在交易")
            return
        h = Stock(stock,context)
        if not  h.is_hold():
            log.info("{} 符合低价策略，买入1成仓".format(stock))
            buy_stock(h.name,my_account,context)